#include "filecache.h"
#include "log.h"


namespace Database
{

using namespace Logging;


FileCache::FileCache(const uint64_t cache_size, const uint64_t block_size)
	: cache_(cache_size, block_size)
{ }


FileCache::~FileCache()
{
	for(filelist_map_t::iterator i = files_.begin(); i != files_.end(); ++i)
		delete i->second;

	files_.clear();
}


bool FileCache::acquire(const char * const pathname)
{
	mutex_.lock();
	filelist_map_t::const_iterator i = files_.find(pathname);

	if(i == files_.end())
	{
		Log(LL_DEBUG) << "Opening file '" << pathname << "'";

		File *pf = new File(pathname);
		if(pf->isOpen())
			files_[pathname] = pf;
		else
		{
			mutex_.unlock();
			return false;
		}
	}
	else
	{
		Log(LL_DEBUG) << "File '" << pathname << "' is already open";
		i->second->incRef();
	}
	mutex_.unlock();

	return true;
}


void FileCache::release(const char * const pathname)
{
	mutex_.lock();
	filelist_map_t::iterator i = files_.find(pathname);

	if(i != files_.end())
	{
		i->second->decRef();
		if(!i->second->isOpen())
		{
			// TODO: delete cache entries relating to this file
			Log(LL_DEBUG) << "File '" << pathname << "' is now closed";
			delete i->second;
			files_.erase(i);

		}
		else
		{
			Log(LL_DEBUG) << "File '" << pathname << "' remains open";
		}
	}
	mutex_.unlock();
}

}	// namespace Database

